package com.wangtianxiang.sxp.weixin.web;

import com.alibaba.fastjson.JSON;
import com.baidu.unbiz.fluentvalidator.Result;
import com.wangtianxiang.sxp.cache.utils.RedisUtil;
import com.wangtianxiang.sxp.domain.Jscode2sessionRes;
import com.wangtianxiang.sxp.dto.BindAccountDto;
import com.wangtianxiang.sxp.dto.LoginDto;
import com.wangtianxiang.sxp.po.WxUser;
import com.wangtianxiang.sxp.module.service.WxUserService;
import com.wangtianxiang.sxp.common.domain.User;
import com.wangtianxiang.sxp.domain.UserInfo;
import com.wangtianxiang.sxp.vo.WxUserVo;
import com.wangtianxiang.sxp.weixin.helper.WxHelper;
import com.wangtianxiang.sxp.weixin.utils.JwtTokenUtils;
import com.wangtianxiang.sxp.common.exception.AppException;
import com.wangtianxiang.sxp.common.http.FeedBackBody;
import com.wangtianxiang.sxp.common.http.ResponseEntity;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.wangtianxiang.sxp.common.utils.AESUtils;
import com.wangtianxiang.sxp.common.utils.FluentValidateUtils;
import com.wangtianxiang.sxp.common.utils.MD5Utils;


/**
 * @description
 * @author wangtianxiang
 * @date: 2021/4/21 17:39
 */
@Slf4j
@Api(tags = "用户管理")
@RequestMapping("/api/user")
@RestController
public class WxUserController {


    @Autowired
    private WxUserService wxUserService;

    @Autowired
    private WxHelper wxHelper;

    @Autowired
    private RedisUtil redisUtil;


    @PostMapping(value = "login")
    @ApiOperation(value = "登录")
    public FeedBackBody<WxUserVo> login(@RequestBody LoginDto req){
        WxUserVo wxUserVo = null;
        Result result = FluentValidateUtils.toSimpleValidate(req);
        if (!result.isSuccess()){
            return ResponseEntity.setForParamCheckError(wxUserVo).setDetail(result.getErrors().get(0));
        }
        Jscode2sessionRes res = wxHelper.code2sessionKey(req.getCode());

        log.info("res:{}", JSON.toJSONString(res));

        if(!StringUtils.isEmpty(res.getErrcode())){//失败
            throw new AppException("内部错误,请重试");
        }

        WxUser user = wxUserService.getById(res.getOpenid());
        if(user == null){
            throw new AppException("用户信息不存在 请先授权获取用户信息");
        }
        User jwtUser = new User();
        jwtUser.setId(res.getOpenid());

        String token = JwtTokenUtils.generateToken(jwtUser);
        redisUtil.set(token,JSON.toJSONString(user));
        return ResponseEntity.setForSuccess(new WxUserVo(user,token));
    }

    @PostMapping(value = "bindAccount")
    @ApiOperation(value = "绑定账号")
    public FeedBackBody<WxUserVo> bindAccount(@RequestBody BindAccountDto req){
        WxUserVo wxUserVo = null;
        try {
            //1、参数校验
            Result result = FluentValidateUtils.toSimpleValidate(req);
            if (!result.isSuccess()){
                return ResponseEntity.setForParamCheckError(wxUserVo).setDetail(result.getErrors().get(0));
            }

            Jscode2sessionRes res = wxHelper.code2sessionKey(req.getCode());

            log.info("res:{}", JSON.toJSONString(res));

            if(!StringUtils.isEmpty(res.getErrcode())){//失败

                return ResponseEntity.setForServiceError();

            }

            String signature = MD5Utils.sha(req.getRawData() + res.getSession_key());
            if(!signature.equals(req.getSignature())){
               throw new AppException("用户数据非法篡改");
            }

            UserInfo userInfo = JSON.parseObject(req.getRawData(),UserInfo.class);


            //查询数据库是否有id
            WxUser user = wxUserService.getById(res.getOpenid());
            WxUser newUser = new WxUser();
            newUser.setOpenid(res.getOpenid());
            newUser.setNickname(userInfo.getNickName());
            newUser.setAvatarUrl(userInfo.getAvatarUrl());
            newUser.setGender(userInfo.getGender());
            newUser.setCountry(userInfo.getCountry());
            newUser.setProvince(userInfo.getProvince());
            newUser.setCity(userInfo.getCity());
            if(user == null){//自动注册
                wxUserService.save(newUser);
            }else{
                wxUserService.updateById(newUser);
                newUser.setBirthday(user.getBirthday());
                newUser.setAddress(user.getAddress());
                newUser.setCreateTime(user.getCreateTime());
                newUser.setUpdateTime(user.getUpdateTime());
            }
            User jwtUser = new User();
            jwtUser.setId(res.getOpenid());

            String token = JwtTokenUtils.generateToken(jwtUser);
            redisUtil.set(token,JSON.toJSONString(newUser));
            return ResponseEntity.setForSuccess(new WxUserVo(newUser,token));
        }catch (Exception e){
            log.error("WxUserController.login error:{}",e);
            return ResponseEntity.setForServiceError();
        }

    }

    public static void main(String[] args) throws Exception {

        String encryptedData = "4FJnzyH/KEZlPEa8nuuWk0pUf/ga0OLpLgsbF1yI57tjDSHuOhnaENGKc5FtC+enjWOiBDofkCArPJPWWPS0GcfOrGqfG1vPz6Zt442H26cqf8bnzWtdDjNe6BUTS2fBTPIPgwYMF2KcEi3w+G2Go8r0JepPwKLPL9IqkSU8pRP0I8zl5/7enXgo2ZoYP+PD6cG+XYRn67g07rwwE65Y5kN3jNZnuea0cGKqxSY2C+5PDl95I8OEouCK2mfDt9cFQij0b30RCWqzbZBNqLVFscJpW1t6s54mTWSFGoc7kGxofOouvlU4cQvgOU0MGSErp80Gb562pXLESFW1YWLiMVl2mPx0V1ZH7OirfpWGkMn6dMbu0KSyKupt4+g4pX4xJVQKkr/s9z/jAi5s0zmkLXQmzb0x0MpMfjXWGtLyGYn/Ryj8U0uHtQ08uSzXCnn2D9ueOf1J2xw+0qmwTwWDkQ==";
        String iv = "RxsksHcKHMDH4SQ9eKtx8A==";
        String session_key = "9jCsQEOgkBkWREXh1qSW7w==";
        String data = AESUtils.decrypt(encryptedData, session_key, iv, "UTF-8");
        System.out.println(data);

    }
}
